//
//  WTSquareDetailViewController.m
//  OneDay
//
//  Created by lanou on 16/1/15.
//  Copyright © 2016年 小明. All rights reserved.
//

#import "WTSquareDetailViewController.h"
#import "WTCommentTableViewCell.h"
#import "WTRequestManager.h"
#import "WTAboutNewsModel.h"
#import "WTRecommendDetailModel.h"
#import <UIImageView+WebCache.h>
#import <UIButton+WebCache.h>
#import "WTSquarePictureDetailViewController.h"
#import <MJRefresh.h>
#import <MBProgressHUD.h>
#import "WTSquareFootView.h"
#import "WTPublishCommentViewController.h"
#import <UMSocial.h>
#import <WebKit/WebKit.h>
#import <UMSocialWechatHandler.h>
#import <UMSocialQQHandler.h>



#define kMargin 10 * kRelativeLength_X

@interface WTSquareDetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) UITableView * tableView;

// tableView的表头
@property (nonatomic, strong) UIView * headView;

// 作者名
@property (nonatomic, strong) NSString * author;
// 头像
@property (nonatomic, strong) NSString * userImg;
// 时间
@property (nonatomic, strong) NSString * publishTime;
// 标题
@property (nonatomic, strong) NSString * detailTitle;
// 赞
@property (nonatomic, strong) NSString * laud;
// 那些人赞
@property (nonatomic, strong) NSString * laudList;
// 图片网址的数组
@property (nonatomic, strong) NSMutableArray *imgArray;
// 内容
@property (nonatomic, strong) NSString * webContent;

// 分享的网址
@property (nonatomic, strong) NSString * shareUrl;

// 存放图片的数组
@property (nonatomic, strong) NSMutableArray * imageArray;

// 热门的数组
@property (nonatomic, strong) NSMutableArray * hotCommentArray;
// 所有评论的数组
@property (nonatomic, strong) NSMutableArray * allCommentArray;

// 表头的高度
@property (nonatomic, assign) CGFloat headHeight;

// 网络请求从第几个开始
@property (nonatomic, assign) NSInteger  requestStart;

// 等待数据加载完成动画
@property (nonatomic, strong) MBProgressHUD * hud;


// 下面有评论的底部视图
@property (nonatomic, strong) WTSquareFootView * footView;

// 发布评论的控制器
@property (nonatomic, strong) WTPublishCommentViewController * publishVC;
@end

@implementation WTSquareDetailViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
  
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"COMMENT" object:self];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"详情";
    self.tabBarController.tabBar.hidden = YES;
    _requestStart = 1;
    
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, self.view.height - 49) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[WTCommentTableViewCell class] forCellReuseIdentifier:@"WTCommentTableViewCell"];
    
#pragma mark -- 明杰刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _requestStart = 1;
        [self requestData];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _requestStart++;
        [self requestData];
    }];
    
    
    _hotCommentArray = [NSMutableArray array];
    _allCommentArray = [NSMutableArray array];
   
    [self setupData];
    [self requestData];
    
    [self setupHud];
    
    
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:@"COMMENT" object:nil];
    // Do any additional setup after loading the view.
}
- (void)notification:(NSNotification *)notification
{
    _requestStart = 1;
    [self requestData];
}
#pragma mark -- 等待数据加载完成的动画
- (void)setupHud
{
    _hud = [[MBProgressHUD alloc]initWithView:self.view];
    _hud.frame = self.view.bounds;
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.labelText = @"正在努力加载中...";
    [self.view addSubview:_hud];
    [_hud show:YES];
}

#pragma mark -- 添加底部视图
- (void)addFootView
{
    _footView = [[WTSquareFootView alloc]initWithFrame:CGRectMake(0, kScreenHeight - 49, kScreenWidth, 49)];
    _footView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_footView];

    
    [_footView.commentButton addTarget:self action:@selector(publishComment:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [_footView.shareButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)publishComment:(UIButton *)button
{
    _publishVC = [[WTPublishCommentViewController alloc]init];
    _publishVC.tid = _tid;
    _publishVC.fid = _fid;
    [self presentViewController:_publishVC animated:YES completion:nil];
}

#pragma mark -- 分享的方法
- (void)shareButtonClick:(UIButton *)button
{
    [UMSocialWechatHandler setWXAppId:@"wx2efc3516108c521f" appSecret:@"20ff141b8337683d3a92665e1000750d" url:_shareUrl];
    [UMSocialQQHandler setQQWithAppId:@"1105058057" appKey:@"hYD0bP3xKobtMo3O" url:_shareUrl];
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"56a041f0e0f55a55880002f5" shareText:[NSString stringWithFormat:@"%@          %@",_detailTitle,_shareUrl] shareImage:[UIImage imageNamed:@"icon.png"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToWechatTimeline ,UMShareToQQ,nil] delegate:nil];

}


// 添加tableView的表头
- (void)addHeadView
{
    _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 300 * kRelativelength_Y)];
    _headView.backgroundColor = [UIColor whiteColor];
   
   
   
    // 作者头像
    UIImageView * authorImageV = [[UIImageView alloc]initWithFrame:CGRectMake(kMargin, 30 * kRelativelength_Y, 40 *kRelativeLength_X, 40 * kRelativeLength_X)];
    authorImageV.layer.cornerRadius = 20 * kRelativeLength_X;
    authorImageV.layer.masksToBounds = YES;
    [authorImageV sd_setImageWithURL:[NSURL URLWithString:_userImg] placeholderImage:[UIImage imageNamed:@"m-zanweitu"]];
    [_headView addSubview:authorImageV];
    
    // 作者姓名
    UILabel * authorLabel = [[UILabel alloc]initWithFrame:CGRectMake(authorImageV.right +kMargin, authorImageV.top, 200 * kRelativeLength_X, 20 * kRelativeLength_X)];
    authorLabel.text = _author;
    authorLabel.textColor = [UIColor blueColor];
    [_headView addSubview:authorLabel];
    
    
    // 将时间间隔转化为日期进行展示
    NSInteger interval = [_publishTime integerValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSString *dateString = [NSString stringWithFormat:@"%@",date];
    NSString * str = [dateString substringToIndex:19];
    
    // 发布日期
    UILabel * publishTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(authorLabel.left, authorLabel.bottom + kRelativelength_Y, 200 * kRelativeLength_X, 16 * kRelativelength_Y)];
    publishTimeLabel.font = [UIFont systemFontOfSize:13];
    publishTimeLabel.text = str;
    [_headView addSubview:publishTimeLabel];
    
    // 自适应标题的高度
    NSDictionary * titleDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19],NSFontAttributeName, nil];
    
    CGRect titleFram = [_detailTitle boundingRectWithSize:CGSizeMake(kScreenWidth - 2 * kMargin, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:titleDic context:nil];
    // 标题
    UILabel * titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(authorImageV.left,authorImageV.bottom + 20 * kRelativelength_Y, kScreenWidth - authorImageV.left, titleFram.size.height)];
    titleLabel.font = [UIFont systemFontOfSize:19];
    titleLabel.text = _detailTitle;
    titleLabel.numberOfLines = 0;
    [_headView addSubview:titleLabel];
    
    
    // 自适应内容的高度
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
    
    CGRect fram = [_webContent boundingRectWithSize:CGSizeMake(kScreenWidth - 2 * kMargin, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    // 内容
    UILabel * contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(titleLabel.left, titleLabel.bottom + 20 * kRelativelength_Y, kScreenWidth - kMargin * 2, fram.size.height)];
    contentLabel.font = [UIFont systemFontOfSize:16];
    contentLabel.text = _webContent;
    contentLabel.numberOfLines = 0;
    [_headView addSubview:contentLabel];
    
    
    _headHeight = contentLabel.bottom;
    
    // 初始化图片的数组
    _imageArray = [NSMutableArray array];
    // 循环创建button
    for (int i = 0; i < _imgArray.count; i++) {
        
        //  获取到网络上图片的长高
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_imgArray[i]]];
        UIImage * image = [UIImage imageWithData:data];
        
      
        
        UIButton * button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        
        // 判断图片的宽度
        // 1.比屏幕的宽长的话,给一个定值,并根据比例调整图片的高度
        // 2.没有屏幕的宽长的话, 不改变图片的宽高
        if (image.size.width >= kScreenWidth - 2 *kMargin) {
            CGFloat width = (kScreenWidth - 2 * kMargin);
            CGFloat buttonHeight = image.size.height / image.size.width * width;
            button.frame = CGRectMake(kMargin, _headHeight + 10 * kRelativelength_Y, width, buttonHeight);
            _headHeight = _headHeight + 10 * kRelativelength_Y + buttonHeight;
            
            [_imageArray addObject:image];
        }else if(image!= nil){
            
            button.frame = CGRectMake(kMargin, _headHeight + 10 * kRelativelength_Y, image.size.width,image.size.height);
            _headHeight += 10 * kRelativelength_Y + image.size.height;
            
            [_imageArray addObject:image];
        }
        button.tag = 100 + i;
        
        
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:_imgArray[i]] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"m-zanweifu"]];
        // 给按钮添加方法, 点击图片后,跳转到另一个展示图片的控制器
        [button addTarget:self action:@selector(bringImageToICarousel:) forControlEvents:(UIControlEventTouchUpInside)];
        [_headView addSubview:button];
       
    }
    
    
    NSString * laudContent =  [NSString stringWithFormat:@"%@...%@人赞过", _laudList,_laud];
    // 自适应laudList的高度
    NSDictionary * laudDic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil];
    
    CGRect laudFram = [laudContent boundingRectWithSize:CGSizeMake(kScreenWidth -  kMargin - 30 * kRelativeLength_X, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:laudDic context:nil];
  
    // 哪些人赞过
    UILabel * laudList = [[UILabel alloc]init];
    laudList.numberOfLines = 0;
    laudList.font = [UIFont systemFontOfSize:14];
    if (![_laudList isEqualToString:@" "] && _laudList != nil ) {
        laudList.frame = CGRectMake(40 * kRelativeLength_X, _headHeight + 20 * kRelativelength_Y, kScreenWidth - kMargin - 40 * kRelativeLength_X, laudFram.size.height);
        laudList.text = laudContent;
        _headHeight += laudList.height + 20 * kRelativelength_Y;
    }else {
        laudList.frame = CGRectMake(40 * kRelativeLength_X, _headHeight + 20 * kRelativelength_Y, kScreenWidth - kMargin - 40 * kRelativeLength_X, 20 * kRelativelength_Y);
        laudList.text = @"还没有人赞过";
        _headHeight += laudList.height + 20 * kRelativelength_Y;
    }
   
     [_headView addSubview:laudList];
   
    // 赞
    UIImageView * zanImageV = [[UIImageView alloc]initWithFrame:CGRectMake(kMargin, (laudList.height - 20 *  kRelativelength_Y) / 2 + laudList.top, 20 * kRelativeLength_X, 20 * kRelativelength_Y)];
    zanImageV.image =[UIImage imageNamed:@"m-zan"];
    [_headView addSubview:zanImageV];
    
    
    _headView.frame = CGRectMake(_headView.left, _headView.top, _headView.width, _headHeight + 20 * kRelativelength_Y);
    
     _tableView.tableHeaderView = _headView;
}

#pragma mark -- 点击跳转到详细展示界面的方法
- (void)bringImageToICarousel:(UIButton *)button
{
    WTSquarePictureDetailViewController * pictureDetailVC = [[WTSquarePictureDetailViewController alloc]init];
    pictureDetailVC.index = button.tag - 100;
    pictureDetailVC.imageArray = _imageArray;
    
    [self.navigationController pushViewController:pictureDetailVC animated:YES];
}

// 网络请求
- (void)setupData
{

    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"tid"] = _tid;
    dic[@"fid"] = _fid;
    dic[@"flag"] = @"1";
    dic[@"plat"] = @"android";
    dic[@"proct"] = @"mierapp";
    dic[@"versioncode"] = @"20150807";
    dic[@"apiCode"] = @"4";
    
    [WTRequestManager requestWithUrlString:@"http://bbs.mier123.com/api/quanzi/viewthread_json.php?plat=android&proct=mierapp&versioncode=20150807&apiCode=4" parDic:dic method:POST success:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        // ------------------- 解析数据,将相关新闻转化为model
        NSArray * hotArray = dic[@"hotCommentList"];
        for (NSDictionary * oneDic in hotArray) {
            WTRecommendDetailModel * model = [[WTRecommendDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_hotCommentArray addObject:model];
        }
        
        // 赋值
        _detailTitle = dic[@"title"];
        _author = dic[@"author"];
      
        _publishTime = dic[@"publishTime"];
        _laud = dic[@"laud"];
        _laudList = dic[@"laudList"];
        _userImg = dic[@"userImg"];
        _imgArray = dic[@"imgArr"];
        _webContent = dic[@"webContent"];
        _shareUrl = dic[@"url"];
        
         [self addHeadView];
        [self addFootView];

    } error:^(NSError *error) {
        
    }];

}

#pragma mark -- 所有评论的刷新
- (void)requestData
{
//  http://bbs.mier123.com/api/quanzi/feedback.php?plat=android&proct=mierapp&versioncode=20150807&apiCode=4
//tid=1921304&fid=683&page=4&plat=android&proct=mierapp&versioncode=20150807&apiCode=4

    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    dic[@"tid"] = _tid;
    dic[@"fid"] = _fid;
    dic[@"page"] = [NSString stringWithFormat:@"%ld",(long)_requestStart];
    dic[@"plat"] = @"android";
    dic[@"proct"] = @"mierapp";
    dic[@"versioncode"] = @"20150807";
    dic[@"apiCode"] = @"4";
    
    [WTRequestManager requestWithUrlString:@"http://bbs.mier123.com/api/quanzi/feedback.php?plat=android&proct=mierapp&versioncode=20150807&apiCode=4" parDic:dic method:POST success:^(NSData *data) {
        
        
        if (_requestStart == 1) {
            [_allCommentArray removeAllObjects];
        }
        
        NSDictionary * dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray * allCommentListArr = dataDic[@"commentList"];
        for (NSDictionary * oneDic in allCommentListArr) {
            WTRecommendDetailModel * model = [[WTRecommendDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_allCommentArray addObject:model];
        }
          [_hud hide:YES];
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
      
    } error:^(NSError *error) {
        
    }];
    
}



#pragma mark -- 数据源方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_hotCommentArray.count ==0) {
        return 1;
    }else {
        
        return 2;
    }

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_hotCommentArray.count != 0 && section == 0) {
        
        return _hotCommentArray.count;
       
    }else{
        return _allCommentArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WTCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"WTCommentTableViewCell" forIndexPath:indexPath];
    if (_hotCommentArray.count != 0 && indexPath.section == 0) {
        cell.model = _hotCommentArray[indexPath.row];
    }else {
        cell.model = _allCommentArray[indexPath.row];
    }
    return cell;
}

// 返回分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0 && _hotCommentArray.count != 0) {
        return @"精彩评论";
    } else if(_allCommentArray.count != 0){
        return @"全部评论";
    }else{
        return nil;
    }
}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 判断有没有精彩评论
    
    if (indexPath.section == 0 && _hotCommentArray.count != 0) {
        return [WTCommentTableViewCell heightForRowWithModel:_hotCommentArray[indexPath.row]];
    }else {
     return [WTCommentTableViewCell heightForRowWithModel:_allCommentArray [indexPath.row]];
    }
   
}
   
   
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
